package nju.bishe.weibo;

import java.util.List;

import nju.bishe.weibo.adapter.UserArrayAdapter;
import nju.bishe.weibo.adapter.UserTokenAdapter;
import nju.bishe.weibo.data.OAuthConstant;
import nju.bishe.weibo.data.UserToken;
import nju.bishe.weibo.data.db.UserTokenTable;
import nju.bishe.weibo.task.GenericTask;
import nju.bishe.weibo.task.TaskAdapter;
import nju.bishe.weibo.task.TaskListener;
import nju.bishe.weibo.task.TaskParams;
import nju.bishe.weibo.task.TaskResult;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class LoginActivity extends Activity {

	// private static final String CLASSTAG =
	// LoginActivity.class.getSimpleName();

	private UserTokenAdapter userTokenWrapperAdapter;
	private List<UserToken> userTokens;
	private ListView listView;
	private ImageButton addIcon;
	private ImageButton delIcon;
	private ImageButton exitIcon;
	protected ListView mUserList;
	protected UserArrayAdapter mUserListAdapter;

	Intent intent;
	GenericTask mLoginTask;
	private TaskListener mLoginListener = new TaskAdapter() {

		@Override
		public void onPostExecute(GenericTask task, TaskResult result) {

			listView = (ListView) findViewById(R.id.login_list);
			listView.setItemsCanFocus(false);
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long id) {
					Bundle bundle = new Bundle();
					bundle.putParcelable("existingUser",
							userTokens.get(position));
					Uri uri = Uri.parse("bishe://OAuthActivity");
					Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
			if ((userTokens == null) || (userTokens.size() == 0)) {
			} else {
				userTokenWrapperAdapter = new UserTokenAdapter(
						LoginActivity.this, userTokens);
				listView.setAdapter(userTokenWrapperAdapter);
			}
		}

		@Override
		public String getName() {
			return "LoginTask";
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.login);
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		System.setProperty("weibo4j.oauth.consumerSecret",
				Weibo.CONSUMER_SECRET);

		setLoginTitle();

		addIcon = (ImageButton) findViewById(R.id.addIcon);
		delIcon = (ImageButton) findViewById(R.id.delIcon);
		exitIcon = (ImageButton) findViewById(R.id.exitIcon);

		addIcon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 动画
				Animation anim = AnimationUtils.loadAnimation(v.getContext(),
						R.anim.scale_lite);
				v.startAnimation(anim);

				System.setProperty("weibo4j.oauth.consumerKey",
						Weibo.CONSUMER_KEY);
				System.setProperty("weibo4j.oauth.consumerSecret",
						Weibo.CONSUMER_SECRET);
				Weibo weibo = OAuthConstant.getInstance().getWeibo();
				RequestToken requestToken;
				try {
					requestToken = weibo
							.getOAuthRequestToken("bishe://OAuthActivity");
					Uri uri = Uri.parse(requestToken.getAuthenticationURL()
							+ "&from=xweibo");
					OAuthConstant.getInstance().setRequestToken(requestToken);

					startActivity(new Intent(Intent.ACTION_VIEW, uri));
				} catch (WeiboException e) {
					e.printStackTrace();
				}
			}
		});

		delIcon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ImageView spaceshipImage = (ImageView) findViewById(R.id.addIcon);
				Animation anim = AnimationUtils.loadAnimation(
						spaceshipImage.getContext(), R.anim.scale_lite);
				spaceshipImage.startAnimation(anim);

				startActivity(new Intent(LoginActivity.this,
						DelAccountActivity.class));
			}
		});

		exitIcon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Dialog dialog = new AlertDialog.Builder(LoginActivity.this)
						.setTitle("警告")
						.setMessage("你确定退出吗？")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										Intent startMain = new Intent(
												Intent.ACTION_MAIN);
										startMain
												.addCategory(Intent.CATEGORY_HOME);
										startMain
												.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										startActivity(startMain);
										System.exit(0);
									}
								})
						.setNeutralButton("取消",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										dialog.dismiss();
									}
								}).create();

				dialog.show();
			}
		});
		mLoginTask = new LoginTask();
		mLoginTask.setListener(mLoginListener);
		mLoginTask.execute();
	}

	public void setLoginTitle() {
		TextView title = (TextView) findViewById(R.id.login_title);
		//title.setBackgroundDrawable( new BitmapDrawable());
		title.setBackgroundResource(android.R.color.transparent);

		LayoutParams lp = new LayoutParams(
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		lp.setMargins(3, 12, 0, 0);
		title.setLayoutParams(lp);
		// 中文粗体
		TextPaint tp = title.getPaint();
		tp.setFakeBoldText(true);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	protected void onStart() {
		super.onRestart();
		Intent intent = getIntent();
		if (intent.hasExtra("finish")) {
			Intent startMain = new Intent(
					Intent.ACTION_MAIN);
			startMain
					.addCategory(Intent.CATEGORY_HOME);
			startMain
					.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(startMain);
			System.exit(0);
		}
	}
	private class LoginTask extends GenericTask {

		@Override
		protected TaskResult _doInBackground(TaskParams... params) {

			UserTokenTable dbHelper = new UserTokenTable(LoginActivity.this);
			userTokens = dbHelper.getAllUsersRemember();
			return TaskResult.OK;
		}
	}
}
